package com.jule.chat.network.handler;

import com.jule.chat.network.FunctionFactory;
import com.jule.chat.network.protocol.Request;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author xujian
 */
public class BinaryWebSocketFrameHandler extends SimpleChannelInboundHandler<BinaryWebSocketFrame> {
    private final static Logger logger = LoggerFactory.getLogger(BinaryWebSocketFrameHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        Channel incoming = ctx.channel();
        logger.debug("Client:" + incoming.remoteAddress() + "在线");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        Channel incoming = ctx.channel();
        logger.debug("Client:" + incoming.remoteAddress() + "掉线");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        Channel incoming = ctx.channel();
        logger.debug("Client:" + incoming.remoteAddress() + "异常");
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, BinaryWebSocketFrame msg) {
        ByteBuf byteBuf = msg.content();
        int length = byteBuf.readInt();
        int functionId = byteBuf.readInt();
        int tmp1 = byteBuf.readInt();
        int tmp2 = byteBuf.readInt();
        //todo length check
        logger.debug("length = " + length);
        logger.debug("func = " + functionId);
        logger.debug("tmp1 = " + tmp1);
        logger.debug("tmp2 = " + tmp2);
        logger.debug("remain" + byteBuf.readableBytes());
        Request request = FunctionFactory.getInstance().getRequest(functionId, ctx);
        if (request != null && request.readPayLoad(byteBuf)) {
            ctx.fireChannelRead(request);
        }
    }
}
